$(function () {
    let $startTime = $("input[name='start_time']");
    let $endTime = $("input[name='end_time']")

    let config = {
        // 自动关闭
        autoclose: true,
        // 日期格式
        format: 'yyyy/mm/dd',
        // 选择语言为中文
        language: 'zh-CN',
        // 优化样式
        showButtonPanel: true,
        // 高亮今天
        todayHighlight: true,
        // 是否在周行的左侧显示周数
        calendarWeeks: true,
        // 清除
        clearBtn: true,
        // 0 ~11  网站上线的时候
        startDate: new Date(2018, 10, 1),
        // 今天
        endDate: new Date(),
    }
    $startTime.datepicker(config);
    $endTime.datepicker(config);

    let $deleteNews = $(".btn-del");
    $deleteNews.click(function () {
        let id = $(this).data("news-id");
        console.log(id);
        $.ajax({
            url: "/x-admin/news/" + id + "/",
            type: "DELETE",
            dataType: "json"
        })
            .done(function (res) {
                if(res.errno === "0"){
                    fAlert.alertSuccessToast("删除成功");
                    setTimeout(function () {
                        window.location.reload();
                    }, 1000)
                }
                else{
                    fAlert.alertErrorToast(res.errmsg);
                }
            })
            .fail(function (res) {
                fAlert.alertErrorToast("网络出了问题，请刷新重试")
            })
    })

    function getCookie(name) {
        let cookieVaalue = ""
        if(document.cookie && document.cookie!==""){
            let cookies = document.cookie.split(";");
            for(let i=0;i<cookies.length;i++){
                let cookie = $.trim(cookies[i]);
                if(cookie.substr(0, name.length + 1)===name+"="){
                    cookieVaalue = decodeURIComponent(cookie.substring(name.length+1))
                    break
                }
            }
            return cookieVaalue
        }
    }

    // these HTTP methods do not require CSRF protection
    function csrfSafeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/).test(method)
    }
    
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if(!csrfSafeMethod(xhr.type) && !this.crossDomain)
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'))
        }
    })

})